package com.tianhao.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tianhao.common.service.RestInterfaceInvokeService;
import com.tianhao.dto.ResultDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author: tianhao.luo@hand-china.com 2021/6/22  下午1:25
 */
@Service
public class RestInterfaceInvokeServiceImpl implements RestInterfaceInvokeService {
    private static final String ACCESS_TOKEN = "access_token";
    private static final String CONTENT_TYPE = "Content-Type";
    private static final String APPLICATION_JSON_CHARSET = "application/json;charset=UTF-8";
    private static final String APPLICATION_JSON = "application/json";
    private static final String APPLICATION_FORM_DATA = "multipart/form-data";
    private static final Logger LOGGER = LoggerFactory.getLogger(RestInterfaceInvokeServiceImpl.class);
    /**
     * 获取token的地址
     */
    String tokenUrl = "http://10.185.62.161:8080/oauth/public/todo/custom-token?loginName=${LOGIN_NAME}&client_id=client&grant_type=implicit";

    /**
     * 文件上传请求
     */
    String interfaceUrl = "http://10.185.62.161:8080/apfm/v1/0/file-upload-logs/asset/upload-file?assetNum=${ASSET_NUM}";
    /**
     * 文件删除接口请求
     */
    String interfaceUrl2 = "http://10.185.62.161:8080/apfm/v1/0/file-upload-logs/asset/delete-file?assetNum=${ASSET_NUM}&fileUrl=${FILE_URL}";
//    String interfaceUrl = "http://localhost:8390/public/v1/0/file-upload-logs/asset/upload-file?assetNum=10";

    private String getToken(String loginName) {
        RestTemplate restTemplate = new RestTemplate();
        String tokenFullUrl = tokenUrl.replace("${LOGIN_NAME}", loginName.toUpperCase());
        LOGGER.info("获取token的url:{}", tokenFullUrl);
        // 1.获取token
        ResponseEntity<String> exchange = restTemplate.exchange(tokenFullUrl, HttpMethod.GET, null, String.class);
        String accessToken = exchange.getBody();
        JSONObject jsonObject = JSON.parseObject(accessToken);
        return jsonObject.getString("token");
    }


    @Override
    public ResultDTO<?> uploadFile(MultipartFile file, String assetNum, String loginName) {
        RestTemplate restTemplate = new RestTemplate();
        // 1.获取用户的token
        String token = getToken(loginName);

        // 2.请求文件上传
        // 2.1需要token放入请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setBearerAuth(token);
        httpHeaders.add("Authorization", "Bearer " + token);
        // 2.2添加表单中的文件请求
        MultiValueMap<String, Object> bodyMap = new LinkedMultiValueMap<>();
        String originalFilename = file.getOriginalFilename();
        // 2.2.1将文件写入本地项目中
        File localFile = new File(originalFilename);
        try (InputStream inputStream = file.getInputStream();
             FileOutputStream fileOutputStream = new FileOutputStream(localFile);
             BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
             BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream)) {
            byte[] temp = new byte[1024];
            int i;
            while ((-1 != (i = bufferedInputStream.read(temp)))) {
                bufferedOutputStream.write(temp, 0, i);
            }
        } catch (Exception e) {
            LOGGER.error("文件写入本地失败:"+e.getMessage());
        }
        // 2.3将文件传给halm
        // 注意file字段名不可随意更改
        bodyMap.add("file", new FileSystemResource(localFile));
        // 2.3.1合并请求头和请求体
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(bodyMap, httpHeaders);
        ResponseEntity<ResultDTO> exchange1 = restTemplate.exchange(interfaceUrl.replace("${ASSET_NUM}", assetNum), HttpMethod.POST, httpEntity, ResultDTO.class);
        // 3.删除本地文件
        if (localFile.delete()) {
            LOGGER.info("本地缓存" + localFile.getName() + "文件删除成功!");
        }
        return exchange1.getBody();
    }

    @Override
    public ResultDTO<?> deleteFile(String fileUrl, String assetNum, String loginName) throws Exception {
        RestTemplate restTemplate = new RestTemplate();
        // 1.获取用户的token
        String token = getToken(loginName);
        HttpHeaders httpHeaders = new HttpHeaders();
        // 2.构造请求头
        httpHeaders.setBearerAuth(token);
        httpHeaders.add("Authorization", "Bearer " + token);
        String url = interfaceUrl2.replace("${ASSET_NUM}", assetNum).replace("${FILE_URL}", fileUrl);
        LOGGER.info("请求halm删除文件的接口为地址:{}",url);
        // 3.合并请求头
        HttpEntity<Object> entity = new HttpEntity<>(httpHeaders);
        ResponseEntity<ResultDTO> exchange1 = restTemplate.exchange(url, HttpMethod.POST, entity, ResultDTO.class);
        return exchange1.getBody();
    }
}
